﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace CoolCode.Web
{
    /*例子：
		<httpHandlers>
           <add verb="*" path="Upload/*.*" type="TRE.Web.FileHandler, TRE.Web"/>
		</httpHandlers>
     */

    /// <summary>
    /// 文件Handler 
    /// 默认文件目录："~/Upload"，可通过配置文件配置，配置key是“UploadPath”
    /// </summary>
    public class FileHandler : BaseHandler, IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string requestedFile = context.Request.Url.Segments[context.Request.Url.Segments.Length - 1];
                if (HasPermission(context, requestedFile))
                {
                    // Set the content type
                    string file = Path.Combine(Config.UploadPath, requestedFile);
                    if (System.IO.File.Exists(file))
                    {
                        string fileName = requestedFile;
                        HttpResponse response = context.Response;
                        response.Clear();
                        response.ContentType = ContentType(requestedFile);
                        response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                        response.WriteFile(file);
                        response.Flush();
                        response.Close();
                        response.End();
                    }
                    else
                    {
                        throw new FileNotFoundException("Cannot found this file: " + requestedFile);
                        //this.ViewError("E0024"); 
                    }
                }
                else
                {
                    //this.ViewError("E0025");
                    throw new UnauthorizedAccessException("User does not have permission to access this file.");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw ex;
            }
        }


        private bool HasPermission(HttpContext context, string Filename)
        {
            try
            {
                //if (!context.User.Identity.IsAuthenticated)
                //    return false;
                return true;
            }
            catch
            {
                return false;
            }
        }


        private string ContentType(string filename)
        {
            int dotIndex = filename.IndexOf(".");
            if (dotIndex == -1)
            {
                return "text/plain";
            }
            else
            {
                string extension = filename.Substring(dotIndex);
                switch (extension)
                {
                    //case ".exe":
                    //    return "application/octet-stream";
                    //case ".txt":
                    //    return "text/plain";
                    //case ".jpg":
                    //case ".jpeg":
                    //case ".png":
                    //case ".gif":
                    //case ".bmp":
                    //    return "image";
                    default:
                        return "application";
                    //throw new NotSupportedException("Unknown extension");
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
